/**
 * Created on 15/5/26.
 */
$.fn.dataTable = function(config){

    var $that = this;
    var $head = $('<thead></thead>').appendTo($that);
    var $body = $('<tbody></tbody>').appendTo($that);

    var loading = {
        loading: function(msg){
            console.log(msg);
        },
        done: function(msg){
            console.log(msg);
        }
    };

    this.columns = config.columns;
    this.ds = new  dataSource();
    function createHead(){
        loading.loading('table head is creating');
        var html, column;
        html = '<tr>';
        for(var i = 0; i < $that.columns.length; i++){
            column = $that.columns[i];
            html += '<th>' + column.title + '</th>';
        }
        html += '</tr>';
        $head.append(html);
        loading.done('table head is created');
    }
    function createTrs(){
        $body.html('');
        loading.loading('table body is creating');
        for(var i = 0; i < $that.ds.list.length; i++){
            var $tr = (function(item){
                var $tr = $('<tr></tr>');
                createTds($tr, item);
                return $tr;
            })($that.ds.list[i]);
            $body.append($tr)
        }
        loading.done('table body is created');
    }
    function createTds($tr, item){
        var html, column, value, action;
        for(var i = 0; i < $that.columns.length; i++){
            (function(column){
                if(column.actions){
                    var $td = $('<td' + getClassName(column) + '></td>');
                    for(var j = 0; j < column.actions.length; j++){
                        (function(action){
                            switch (action.action){
                                case 'edit':
                                    $('<a href="javascript:void(0);" class="btn">编辑</a>').appendTo($td).on('click', function(){
                                        item.start_city_name = '北京';
                                        item.end_city_name = '广州';
                                        $that.ds.update(item, function(){
                                            action.callback(item);
                                            $tr.html('');
                                            createTds($tr, item);
                                        });
                                    });
                                    break;
                                case 'delete':
                                    $('<a href="javascript:void(0);" class="btn">删除</a>').appendTo($td).on('click', function(){
                                        $that.ds.delete('id', item.id, function(){
                                            $tr.remove();//删除dom
                                        });//删除object
                                    });
                                    break;
                                default:
                                    break;
                            }
                        })(column.actions[j]);
                    }
                    $td.appendTo($tr);
                }else{
                    createTd(column, item, $tr);
                }
            })($that.columns[i]);
        }
        function getClassName(column){
            return column.className ? ' class="' + column.className + '"' : '';
        }
        function createTd(column, item, $tr){
            for(var key in item){
                if(column.column == key) {
                    value = item[key];
                    if(column.values){
                        for(var j = 0; j < column.values.length; j++){
                            if(column.values[j].value == value) {
                                value = column.values[j].text;
                            }
                        }
                    }
                    $('<td' + getClassName(column) + '>' + value + '</td>').appendTo($tr);
                }
            }
        }

    }

    function refreshTable(){
        createTrs();
    }

    //init
    (function(){
        createHead();
        //readData();
        $that.ds.read(function(data){
            createTrs(data);
        });
        $('#btn-add').click(function(){
            $that.ds.insert({
                "start_city_name":"\u53f0\u5317",
                "end_city_name":"\u53f0\u5317",
                "start_date":"2015-05-29",
                "end_date":"2015-05-30",
                "status":{"text":"\u672a\u652f\u4ed8",
                    "action":["service_close_order"]},
                "source":"wechat",
                "pay_status":{"text":"\u672a\u652f\u4ed8"},
                "id":"82",
                "total_price":"1959.50",
                "order_code":"15052602882"
            }, function(item){
                refreshTable();
            });

        });
    })();

    return this;
};
var dataSource = function(config){
    //config
    var option = {
        read: {
            url: 'json.php',
            type: 'GET',
            data: null
        },
        update: {
            url: 'json.php',
            type: 'GET',
            data: null
        },
        insert: {
            url: 'json.php',
            type: 'GET',
            data: null
        },
        delete: {
            url: 'json.php',
            type: 'GET',
            data: null
        }
    };
    //config default
    var dataType = 'json';
    //core data
    function data(){ }
    data.prototype.list = new Array();
    data.prototype.read   = function(success){
        var that = this;
        doAjax(option.read.url, option.read.type, option.read.data, function(data){
            that.list = data;
            if(isFunction(success)) success(that.list);
        });
    };
    data.prototype.update = function(dataItem, success){
        var that = this;
        doAjax(option.update.url, option.update.type, dataItem, function(data){
            for(var i = 0; i < that.list.length; i++){
                if(that.list[i] == dataItem){
                    that.list[i] = dataItem;
                }
            }
            if(isFunction(success)) success(dataItem);
        });
    };
    data.prototype.insert = function(dataItem, success){
        var that = this;
        doAjax(option.update.url, option.update.type, dataItem, function(data){
            var temp = [];
            temp[0] = dataItem;
            for(var i = 0; i < that.list.length; i++){
                temp[i + 1] = that.list[i];
            }
            that.list = temp;
            temp = null;
            if(isFunction(success)) success(dataItem);
        });
    };
    data.prototype.delete = function(key, value, success){
        var that = this;
        doAjax(option.update.url, option.update.type, {key: value}, function(data){
            var temp = [];
            var index = 0;
            for(var i = 0; i < that.list.length; i++){
                if(that.list[i][key] != value){
                    temp[index] = that.list[i];
                    index++;
                }
            }
            that.list = temp;
            temp = null;
            if(isFunction(success)) success(data.list);
        });
    };
    //core operation
    //connection with server
    var doAjax = function(url, type, data, success){
        $.ajax({
            url: url,
            type: type,
            dataType: dataType,
            success: success,
            error: ajaxError,
            complete: ajaxComplete
        });
    };
    var ajaxError = function(ex){
        console.log('ajax error');
    };
    var ajaxComplete = function(data){
        console.log('operation done');
    };

    var isFunction = function(fn){
        return typeof(fn) == 'function';
    };

    return new data();
};
